Using OnChange Events to Customize the Data Entry Process

 

Microsoft Corporation

June 2003

Applies to:
    Microsoft® Business Solutions CRM version 1.0

Requires:
     Microsoft Business Solutions CRM version 1.0

Summary: Learn how to use Microsoft Business Solutions CRM OnChange events to add business-specific modifications to the data-entry process. (12 printed pages)

Contents

Introduction
Specifying the Location of an OnChange Event
Creating an OnChange Event
Microsoft CRM Method Used in OnChange Events
Sample 1: Add Message Boxes for Specific Values
Sample 2: Update a Text Field Based on the Drop-Down List Value
Sample 3: Calculate the Freight Cost

Introduction

Microsoft® Business Solutions CRM forms are designed to allow the use of OnChange events for modifying the Microsoft CRM data entry process. This capability means that you can add instructions for the user on the form to make sure data is entered appropriately in the fields or you can make it possible for users to quickly add data to another field. The forms provide a place to add Microsoft JScript code for the OnChange event for any drop-down list (picklist) attribute that is part of a Microsoft CRM customizable entity. The JScript code is run when the user changes the selection in the drop-down list.

OnChange events can be used for a variety of tasks:

  • To provide an alert box notifying users of a special requirement associated with the task.

    For example, adding a new price list might require approval by a finance director. When a user enters a new sales literature item and selects the item type called Price List, an OnChange event could be used to pop up an alert box with information about the required approvals.

  • To set the value of another field on the form.

    For example, when a user enters the rating of an opportunity, the probability field could be filled in automatically according to the value the user selects for the rating.

  • To calculate a value of another field on the form on the basis of information from outside Microsoft CRM.

    For example, when a user creates an order, the choice of shipping method can go to an external database to find the shipping rate for the given method, order size, and ZIP Code and then fill in the Freight field automatically. Because JScript is a client-side language, the OnChange event must call a server-side .aspx page to retrieve information from a database or Web process.

To create a script used in OnChange events, you must have either the Microsoft CRM System Administrator role or another role that includes organization privileges on the object. For more information about roles, see the "Managing User Privileges" in the online help for Microsoft CRM.

Caution   System administrators should have a thorough knowledge of JScript programming syntax and logic before attempting to create OnChange event scripts. Malformed scripts can prevent the form from working correctly.

Because OnChange events are tied to specific fields and specific business logic, you should test them after upgrading or reinstalling Microsoft CRM to make sure the OnChange events and scripts still apply and still function. It is recommended that you document the changes you make and store a copy of your scripts.

This article explains how to use OnChange events with Microsoft JScript and provides three sample scripts to demonstrate the process.

Specifying the Location of an OnChange Event

OnChange events can be set up for any drop-down list in any customizable entity in Microsoft CRM. The entities in Table 1 can have OnChange events for any default, optional, or user-created drop-down list.

Table 1. Customizable Entities

Name of customizable entity as it appears on the Microsoft CRM form Name as it appears in Deployment Manager
Accounts Account
Competitors Competitor
Contacts Contact
Contracts Contracts
Contract Lines in Contracts ContractDetail
Addresses CustomerAddress
Cases Incident
Invoices Invoice
Products in Invoices InvoiceDetail
Leads Lead
Opportunities Opportunity
Products in Opportunities OpportunityProduct
Products Product
Quotes Quote
Products in Quotes QuoteDetail
Orders SalesOrder
Products in Orders SalesOrderDetail
Sales Literature SalesLiterature

Creating an OnChange Event

Creating an OnChange event is a two-phase process:

  1. Writing your JScript for the OnChange event, marking any fields referred to in the script as dependencies, and then testing your changes.

    **Important   **Note the following for this phase of the process:

    • Microsoft CRM does not preserve white space in your script. It is recommended that you write and modify the code in a separate text file and then paste it into the Event tab. This allows you to debug your code in an environment where you can see the structure of your script. Use the/* comment */structure for comments rather than the// commentstructure to avoid having the rest of your code incorporated into the comment.
    • The OnChange event script is part of the script that displays the form, and because of this, errors in the script can change the functionality of other parts of the form. Test your script by adding and updating records; you should repeat the cycle of writing and testing until the script works as expected. Symptoms of script errors include an "Error on page" message in the status bar at the lower left corner of the form, a JScript message box, or a form that doesn't work as expected.
    • Marking a field as a dependency ensures that any field referenced in the script is not deleted inadvertently. It also ensures that if a Quick Create form exists for the object, and if the field with the OnChange event is set as Business Required or Business Recommended in the RequiredLevel field on the Schema tab, the referenced fields are also included in the Quick Create form.
  2. Publishing your modified form by using Microsoft CRM Deployment Manager, and then stopping and restarting all Internet Services. This makes the OnChange event available to all users of Microsoft CRM. Test your script both from your account and from accounts with more limited roles.

The following are the detailed procedures for each phase of creating an OnChange event:

To enter JScript for an OnChange event for a drop-down list

  1. On the Home page, click the Settings side tab.
  2. On the Settings page, click System Customization.
  3. Under Record Management, click the record type you want to customize.
  4. In the Common Tasks area, click Customize Form.
  5. Select a drop-down list (picklist) field, and then click Change Properties.
  6. Click the Events tab, and then click Edit.
  7. On the Details tab, in the text box, enter the JScript you want to enable for the OnChange event.
  8. Select the Event enabled check box to enable the event.
  9. On the Dependencies tab, select any fields that are referenced in the script, and then click OK.
  10. Click OK.
  11. Save your work by clicking Save on the form you are editing.
  12. To preview and test your script, click the Preview menu, and then test your changes using both Create Form and Update Form.

To publish the modified form

  1. On the Microsoft CRM server, on the Start menu, point to Programs, point to Microsoft CRM, and then click Deployment Manager.
  2. On the Action menu, point to All Tasks and then click Publish Customization.
  3. Select the entities in which you added OnChange events, and then click Next.
  4. Click Add.
  5. On the Select Web Servers page, specify the Microsoft CRM servers where you want to publish the changes, and then click Add.
  6. Click Finish, and then click OK.
  7. On the Start menu, click Run.
  8. In the Run box, type IISReset to stop and restart all Internet services, and then click OK.

Microsoft CRM Method Used in OnChange Events

OnChange events can use the crmForm.field.option method to read or write any field on any tab of the current form. Field is the name of the field used in the Microsoft CRM schema. The option is either Value or ReturnValue. The meanings of Value and ReturnValue depend on the data type and are listed in Table 2.

For example, if you are working on the Account form and want to refer to the CustomerTypeCode drop-down list field, you would use crmForm.CustomerTypeCode.Value to refer to the text value of a drop-down list (picklist) item or use crmForm.CustomerTypeCode.ReturnValue to refer to the numeric value of the picklist item. If you want to work with a text field such as Fax, crmForm.Fax.Value points to the data in the Fax field and crmForm.Fax.ReturnValue is undefined.

Table 2. crmForm method options for each data type

Data type Meaning of Value Meaning of Return Value
String Text [Undefined]
Picklist Text in the option (for example: High) Number of the option (for example 1)
Integer Formatted value displayed to the user (for example: 1,000) Unformatted value to be returned to the application (for example: 1000)
Float Formatted value displayed to the user (for example: 5,698.560) Unformatted value to be returned to the application (for example: 5698.56)
Currency Formatted value displayed to the user (for example: 5,698.560) Unformatted value to be returned to the application (for example: 5698.56)
Date/Time Date in preferred date format (for example: 5/7/2003) Date in Coordinated Universal Time (UTC) format (for example: 5/7/2003 12:33:50 AM)
Boolean 1 for TRUE, 0 for FALSE [Undefined]
Memo Text [Undefined]

To determine the ReturnValue number for each item in a drop-down list

  1. In the Customize Form page for the object, select Properties for the field.

  2. On the Values tab, select the first value and click Edit; Repeat this process for each value.

    -OR-

  3. In the Customize Form page for the object, on the View menu, click Field Properties XML.

  4. Scroll down to the drop-down list, and read the information in the <option value> tag.

Sample 1: Add Message Boxes for Specific Values

Training users in the specific procedures for using a business application can be an ongoing challenge, especially with respect to areas of the application that are not used on a daily basis. People often forget the details about how a specific type of transaction should be processed. One easy way to provide context-specific instructions is to create a message box that pops up with further instructions when a user selects an option in a drop-down list. Because pop-up messages can be annoying for users who frequently use a particular form, this type of alert is recommended for infrequently used tasks. In this sample, a pop-up message is used when the user is publishing a new price sheet to Microsoft CRM.

In this sample, JScript is added to the OnChange event for the Type (LiteratureTypeCode) field of the sales literature object so that a pop-up message appears when the user selects Price sheets on the form. In the preceding section "Creating an OnChange Event," follow the steps in the "To enter JScript for an OnChange event for a drop-down list" procedure to add the JScript to the Type field. Enter the following sample code in step 7 of the procedure.

{
/* Use parseInt to convert the number associated with each specific 
   picklist value in the current field (event.srcElement) to an integer. 
     */
switch (parseInt(event.srcElement.returnValue, 10))
{
    /* Price Sheets */
    case 8:
        window.alert('Price sheets must be approved by the Finance 
          Director');
        break;
    /* All other values */
    default:
        window.alert('Sales literature items must be approved 
                      by the District Sales Manager before posting.');
        break;
}

Now publish your changes to the sales literature object by following the procedure "To Publish Your Changes" in the preceding section, "Creating an OnChange Event."

For more information about the JScript used in this sample, see Understanding the Event Model, parseInt Method, and SrcElement Property.

Sample 2: Update a Text Field Based on the Drop-Down List Value

When you have a high volume of data to enter, reducing the amount of data that has to be entered manually can speed up the process, improve the job satisfaction of the person entering the data, and improve the overall quality of the data. An example of reducing manual data entry is when the value in one field on a form determines the value in another field and the second field is updated automatically every time the first field is updated. This sample shows how a change in the Rating field of an opportunity (Hot, Warm, Cold) on the Opportunity form can automatically trigger the loading of data into the Probability field, if the Probability field is empty, reducing the number of fields the person doing data entry must fill out.

The following JScript is added to the OnChange event for the Rating (OpportunityRatingcode) field of the Opportunity form, associating a change in the Rating field with a corresponding value in the Probability (CloseProbability) field. Because this script refers to the Probability field, you should mark Probability as a dependency on the Dependencies tab of the Rating properties.

In the section "Creating an OnChange Event," follow the steps in the "To enter JScript for an OnChange event for a drop-down list" procedure to add the script to the OnChange event for the Rating field and to add the Probability field to the event dependencies. Enter the following sample code in step 7 of the procedure.

var i = 0;
/* Only automatically update the Probability field if it is null. */
if (crmForm.closeprobability.value=='')
{
   /* Convert the number associated with each specific picklist value 
         in the current field to an integer. */
   switch (parseInt(event.srcElement.returnValue, 10))
   {
       /* Hot */
          case 1:
              i = 90;
           break;

       /* Warm */
          case 2:
           i = 60;
           break;

       /* Cold */
          case 3:
           i = 30;
           break;
   }
   crmForm.closeprobability.value = i;
}

Now publish your changes to the opportunity object by following the procedure "To Publish Your Changes" in the section "Creating an OnChange Event."

Sample 3: Calculate the Freight Cost

When you need access to data or calculations that are not built-in to Microsoft CRM, you can get the information by using an OnChange event, which passes data to a server-side page that accesses a separate database or does the calculations and then returns the information to a field on the form. For example, in Microsoft CRM, the freight cost is not calculated automatically because freight costs are determined by different methods in different organizations. However, you can automate this data entry process according to the specific policies of your organization. The freight cost can depend on variables such as the warehouse ZIP Code, the customer's ZIP Code, the weight and size of the item(s) being shipped, and the preferred shipping method. It can also be set to standard charges that are based on the cost of the items being shipped.

In this sample, you modify the order object so that the freight cost, which is going to depend on the weight of the item, is calculated automatically when the Shipping Method is specified. To do this, you add a new integer field called ShippingWeight and then add an OnChange event for when the Shipping Method drop-down list (picklist) value changes so that it updates the Freight value.

This sample has been set up with the OnChange event JScript passing the weight and shipping method to a server-side .aspx page that does the calculations and passes the value back to the OnChange event code. The server-side .aspx page should be set up on a virtual root separate from the Microsoft CRM virtual root so that it is not affected by upgrades to Microsoft CRM.

You can extend this sample by changing the server-side .aspx page to access an external database or Web service.

To modify the order object, you first add a new field called Shipping Weight to the schema for Orders and then add the field to the Order form and define its properties, as shown in the following procedures.

To add a field to the schema for Orders

  1. On the Microsoft CRM server, on the Start menu, point to Programs, point to Microsoft CRM, and then click Deployment Manager.
  2. Expand Schema Manager.
  3. Expand the SalesOrder object, and click Attributes.
  4. On the Action menu, point to New and then click Schema Field.
  5. In the Name box, type ShippingWeight for the new field.
  6. From the Type drop-down list, select integer.
  7. Type values for the Display Name and Description boxes.
  8. Click OK.

To add the field to the Order form and define its properties

  1. Start Internet Explorer and in the browser address box, type the URL you use to connect to Microsoft CRM.
  2. On the Home page, click Settings and then click System Customization.
  3. In Records Management, click Orders.
  4. Click Customize Form, click the Shipping tab, and then click the Shipping Information section.
  5. Click Add Fields.
  6. Select the new field (ShippingWeight) that you just set up in Schema Manager, and then click OK.
  7. Click the new field, and then click Change Properties.
  8. On the Display tab, specify the Name, Label, and Location of the field.
  9. When you are finished adding the new field, click Save.

To set up your server-side aspx page

  1. Using Internet Services Manager, set up a new virtual directory in the Microsoft CRM Version 1.0 Web site. The files for the virtual directory should be set up in a different folder from the Microsoft CRM files.

    For information about how to set up a virtual directory for an ASP.NET Web application, see Walkthrough: Creating an ASP.NET Web Application Root Directory with IIS. The steps in this article refer to creating a new virtual directory in the "Default Web Site." Instead, create the virtual directory in the Microsoft CRM Version 1.0 Web site.

    In the folder for this virtual directory, create a page called Shipping.aspx with the following code that sets up the Web form.

    <%@ Page src="Shipping.aspx.cs" Language="c#" AutoEventWireup="true" Inherits="Shipping.Codes" %>
    

    For more information, see Visual Basic and Visual C# Concepts: Web Forms Code Model and @page Directive.

  2. Set up the code-behind class file Shipping.aspx.cs C# page. This page does the cost calculation and passes the Shipping.Codes to Shipping.aspx. This page expects input of method and weight and returns an XML document with the cost.

The following ASP.NET sample code for the Shipping.aspx.cs page provides costs for just a few values of method and weight. You can replace this with code that accesses a complete external database of shipping costs. For more information about writing ASP.NET code for accessing a database, see the MSDN topic Visual Basic and C# Concepts: Accessing Data.

using System;
using System.Web;

namespace Shipping
{
   public class Codes : System.Web.UI.Page
   {
      private void Page_Load(object sender, System.EventArgs e)
      {
         int cost = 0;
         int weight = Int32.Parse(Request.QueryString["weight"]);
         int method = Int32.Parse(Request.QueryString["method"]);

         switch (method)
         {
            // Airborne
            //
            case 1:
               if (weight < 10)
               {
                  cost = 5;
               }
               else if (weight < 20)
               {
                  cost = 20;
               }
               else
               {
                  cost = 50;
               }
               break;
            // DHL
            //
            case 2:
               if (weight < 20)
               {
                  cost = 10;
               }
               else
               {
                  cost = 50;
               }
               break;

            // Anything else
            //

            default:

               cost = 15;

               break;
         }

         Response.ContentType = "text/xml";
         // Passes an XML document with the cost to the OnChange event
         //
         Response.Write("<cost>" + cost + "</cost>");
      }
   }
}

Now you are ready to add the JScript to the OnChange event for the ShippingMethod field. In the section "Creating an OnChange Event," follow the steps in the "To enter JScript for an OnChange event for a drop-down list". Enter the following sample code in step 7 of the procedure. Replace Microsoft_CRM_server with the name of your Microsoft CRM server, and virtual_directory with the name of the virtual directory you created.in "To Set Up Your Server-Side Aspx Page."

Note that each ampersand (&) in the JScript must be entered as &amp; so that it can be correctly passed to the .aspx page in order to be parsed at the render time of the form. This is because the JScript is stored in the XML form definition.

For more information about the Microsoft.XMLDOM and Msxml2.XMLHTTP objects used in this JScript, see the MSXML 3.0 SDK.

/* Only update the freight amount if there is a value in the Weight field 
  */
if (crmForm.CFIShippingWeight.value!='')
{
  var oXmlDoc           = new ActiveXObject("Microsoft.XMLDOM");
  var oXmlHTTP          = new ActiveXObject("Msxml2.XMLHTTP");

  /* Pass the weight and method in a GET statement to Shipping.aspx. */
  /* Replace "your_virtual_directory" with the location of your 
    Shipping.aspx. */
  oXmlHTTP.Open("GET", 
    "https://Microsoft_CRM_server/virtual_directory/Shipping.aspx?weight=" 
      +
       crmForm.CFIShippingWeight.value + "&amp;method=" +  
       crmForm.shippingmethodcode.returnValue, false);
  oXmlHTTP.Send(oXmlDoc);

  /* Set the freight amount value to the cost passed in from 
    Shipping.aspx.*/
  crmForm.freightamount.value = 
     oXmlHTTP.responseXML.selectSingleNode("cost").text;
  /* Set the freight amount return.Value so the value will persist. */
  crmForm.freightamount.returnValue = 
     oXmlHTTP.responseXML.selectSingleNode("cost").text;
}

Mark ShippingWeight and freightamount as dependencies.

Publish your changes by following the procedure "To Publish Your Changes" in the section "Creating an OnChange Event."